package com.cz.datafetcher.config;

import com.cz.datafetcher.common.CommonReturn;
import com.cz.datafetcher.common.SysError;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class CommonResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if(methodParameter.getMethod().toString().contains("org.springframework.http.ResponseEntity")){
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof CommonReturn) return o;
        return CommonReturn.ok(o);
    }

    //=========错误处理=============
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonReturn handler(Exception e){
        return CommonReturn.error(505,e.getMessage());
    }

    @ExceptionHandler(value = SysError.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonReturn handler(SysError e){
        return CommonReturn.error(400,e.getMessage());
    }
}
